<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入分配任务ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="" prop="inventoryDate">
        <el-date-picker
          clearable
          v-model="queryParams.startDate"
          type="datetime"
          placeholder="进出仓开始日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
        <el-date-picker
          clearable
          v-model="queryParams.endDate"
          type="datetime"
          placeholder="进出仓结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item> -->

      <el-form-item label="" prop="warehouseDocumentNumber">
        <el-input
          v-model="queryParams.warehouseDocumentNumber"
          placeholder="请输入进出仓单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="" prop="lastUpdateTime">
        <el-date-picker
          clearable
          v-model="queryParams.lastUpdateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="" prop="productType">
        <!-- <el-input v-model="form.fieldName" placeholder="请输入字段名" /> -->
        <el-select
          v-model="queryParams.productType"
          placeholder="商品类型"
          clearable
        >
          <el-option label="良品" value="Good" />
          <el-option label="瑕疵" value="Defective" />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="allocationStatus">
        <el-select
          v-model="queryParams.allocationStatus"
          placeholder="分配方案"
          clearable
        >
          <el-option label="待生成" value="toAllocate" />
          <el-option label="已生成" value="isAllocated" />
          <!-- <el-option
            v-for="dict in dict.type.sys_product_allocation_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          /> -->
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="inventoryDate">
        <el-date-picker
          v-model="value2"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="进出仓开始日期"
          end-placeholder="进出仓结束日期"
          :picker-options="pickerOptions"
          @change="changeTime"
          size="mini"
        >
        </el-date-picker>
        <!-- <el-date-picker
          clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="进出仓开始日期"
        >
        </el-date-picker>
        <el-date-picker
          clearable
          v-model="queryParams.endDate"
          placeholder="进出仓结束日期"
          type="date"
          value-format="yyyy-MM-dd 23:59:59"
        >
        </el-date-picker> -->
      </el-form-item>
      <el-form-item label="" prop="dataStatus">
        <el-select
          v-model="queryParams.dataStatus"
          placeholder="数据状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_product_datastatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['productAllocation:BiProductReturnRestock:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['productAllocation:BiProductReturnRestock:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['productAllocation:BiProductReturnRestock:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['productAllocation:BiProductReturnRestock:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handlegenerateBatchAllocationPlan"
          >库存分配</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleGo('/productAllocation/return/abnormalRestock')"
        >
          异常分配记录
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="BiProductReturnRestockList"
      @selection-change="handleSelectionChange"
      :height="500"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分配任务ID" align="center" prop="id" />
      <el-table-column label="商品类型" align="center" prop="productType">
        <template slot-scope="scope">
          <div>
            {{ scope.row.productType | state1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="进出仓日期"
        align="center"
        prop="inventoryDate"
        width="180"
      >
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantityCount" />
      <el-table-column label="分配方案" align="center" prop="allocationStatus"
        ><template slot-scope="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;

              font-weight: bold;
            "
            @click="selectallocationStatus(scope.row)"
          >
            {{ scope.row.allocationStatus | state2 }}
          </span>
        </template>
      </el-table-column>
      <!--  @click="selectproductCode(scope.row)" -->
      <el-table-column label="数据状态" align="center" prop="dataStatus"
        ><template slot-scope="scope">
          <span
            v-if="scope.row.dataStatus == 'abnormal'"
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row)"
            ><dict-tag
              :options="dict.type.sys_product_datastatus"
              :value="scope.row.dataStatus"
          /></span>
          <dict-tag
            v-else
            :options="dict.type.sys_product_datastatus"
            :value="scope.row.dataStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="进出仓单号"
        align="center"
        prop="warehouseDocumentNumber"
      />
      <el-table-column label="商品编码" align="center" prop="productCode">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectproductCode(scope.row)"
            >{{ scope.row.productCode }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="lastUpdateTime"
        width="180"
      >
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['productAllocation:BiProductReturnRestock:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['productAllocation:BiProductReturnRestock:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改销退上架对话框 -->
    <el-dialog
      :visible.sync="openproductCode"
      width="500px"
      append-to-body
      v-if="openproductCode"
    >
      <el-table :data="productCodeList">
        <el-table-column label="店铺" align="center" prop="storeName" />
        <el-table-column label="数量" align="center" prop="quantityCount" />
        <el-table-column label="退货比例" align="center" prop="ratio" />
        <!-- <el-table-column
          label="汇总分配"
          align="center"
          prop="allAllocationCount"
        /> -->
      </el-table>
    </el-dialog>

    <!-- 添加或修改销退上架对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="进出仓日期" prop="inventoryDate">
          <el-date-picker
            clearable
            v-model="form.inventoryDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择进出仓日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进出仓单号" prop="warehouseDocumentNumber">
          <el-input
            v-model="form.warehouseDocumentNumber"
            placeholder="请输入进出仓单号"
          />
        </el-form-item>
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="更新时间" prop="lastUpdateTime">
          <el-date-picker
            clearable
            v-model="form.lastUpdateTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择更新时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="openallocationStatus"
      width="1500px"
      append-to-body
      v-if="openallocationStatus"
    >
      <BiInventoryAllocation :row="row" />
      <!-- <el-table :data="CalcDetailList" border show-summary style="width: 100%">
        <el-table-column prop="shelfId" label="上架ID"> </el-table-column>
        <el-table-column prop="allocatedTime" label="分配时间">
        </el-table-column>
        <el-table-column prop="storeName" label="店铺名称"> </el-table-column>
        <el-table-column prop="totalReturnedQuantity" label="累计退货数量">
        </el-table-column>
        <el-table-column
          prop="historicalAllocationQuantity"
          label="历史累计分配数量"
        >
        </el-table-column>
        <el-table-column prop="summaryAllocatedQuantity" label="汇总分配数量">
        </el-table-column>
        <el-table-column prop="allocatedQuantity" label="本次分配数量">
        </el-table-column> 
      </el-table>-->
    </el-dialog>

    <el-dialog
      :visible.sync="openInfo"
      width="1500px"
      append-to-body
      v-if="openInfo"
    >
      <div class="el-dialog-div">
        <component :is="'abnormalRestock'" :originalTaskId="id"></component>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBiProductReturnRestock,
  getBiProductReturnRestock,
  delBiProductReturnRestock,
  addBiProductReturnRestock,
  updateBiProductReturnRestock,
  generateBatchAllocationPlan,
  getShopReturnNumAndRate,
  listCalcDetail,
} from "@/api/productAllocation/BiProductReturnRestock";

import abnormalRestock from "@/views/productAllocation/abnormalRestock/index.vue";
import BiInventoryAllocation from "@/views/productAllocation/BiInventoryAllocation/select.vue";
import moment from "moment";
export default {
  name: "BiProductReturnRestock",
  dicts: ["sys_product_allocation_status", "sys_product_datastatus"],
  components: {
    BiInventoryAllocation,
    abnormalRestock,
  },
  data() {
    return {
      id: 0,
      openInfo: false,
      openReturnAddress: false,
      CalcDetailList: [],
      row: {},
      openallocationStatus: false,
      productCodeList: [],
      openproductCode: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销退上架表格数据
      BiProductReturnRestockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productType: null,
        inventoryDate: null,
        allocationStatus: null,
        warehouseDocumentNumber: null,
        productCode: null,
        lastUpdateTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value1: "",
      value2: "",
    };
  },
  filters: {
    state1(string) {
      if (string == "Good") {
        return "良品";
      }
      if (string == "Defective") {
        return "瑕疵";
      }
    },
    state2(string) {
      if (string == "allocateSuccess") {
        return "分配成功";
      }
      if (string == "allocateFailure") {
        return "分配失败";
      }
      if (string == "toAllocate") {
        return "待生成";
      }
      if (string == "isAllocated") {
        return "已生成";
      }
    },
  },
  created() {
    this.getList();
  },
  methods: {
    changeTime() {
      // console.log(JSON.stringify(this.value2));
      let m1 = moment(this.value2[0]).format("YYYY-MM-DD");
      let m2 = moment(this.value2[1]).format("YYYY-MM-DD");
      // console.log(JSON.stringify(m1));
      // console.log(JSON.stringify(m2));
      this.queryParams.startDate = m1;
      this.queryParams.endDate = m2;
    },
    selectformisNew(row) {
      this.id = row.id;

      this.openInfo = true;
    },
    handleGo(path) {
      this.$router.push({
        path: path,
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += "";
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    selectallocationStatus(row) {
      this.row = row;
      // listCalcDetail({ pageNum: 1, pageSize: 100, shelfId: row.id }).then(
      //   (response) => {
      //     this.CalcDetailList = response.rows ? response.rows : [];
      //   }
      // );
      this.openallocationStatus = true;
    },
    selectproductCode(row) {
      getShopReturnNumAndRate(row.productCode).then((response) => {
        if (response.length > 0) {
          this.productCodeList = response;
          this.openproductCode = true;
        } else {
          this.$modal.msgError("该款没数量");
        }
      });
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在分配，请稍候！");
    },
    handlegenerateBatchAllocationPlan() {
      if (this.ids.length < 1) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      }
      this.openLoading();
      generateBatchAllocationPlan(this.ids).then((response) => {
        this.$modal.closeLoading();
        if (response.code == 200) {
          this.$modal.msgSuccess("分配成功");
          this.getList();
        }
      });
    },
    /** 查询销退上架列表 */
    getList() {
      this.loading = true;
      listBiProductReturnRestock(this.queryParams).then((response) => {
        this.BiProductReturnRestockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productType: null,
        inventoryDate: null,
        allocationStatus: null,
        warehouseDocumentNumber: null,
        productCode: null,
        lastUpdateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.value2 = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销退上架";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiProductReturnRestock(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销退上架";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiProductReturnRestock(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiProductReturnRestock(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除销退上架编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiProductReturnRestock(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "productAllocation/BiProductReturnRestock/export",
        {
          ...this.queryParams,
        },
        `BiProductReturnRestock_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
